package cn.bluethink.eguan.module.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import cn.bluethink.eguan.core.service.EgTavernService;
import cn.bluethink.eguan.core.service.EgUserService;
import cn.bluethink.eguan.model.core.EgCheckStatus;
import cn.bluethink.eguan.model.module.EgModule;
import cn.bluethink.eguan.model.module.EgModuleObject;
import cn.bluethink.eguan.module.entity.EgModuleEntity;
import cn.bluethink.eguan.module.entity.EgModuleobjectEntity;
import cn.bluethink.eguan.module.mapper.EgModuleMapper;
import cn.bluethink.eguan.module.mapper.EgModuleObjectMapper;
import cn.bluethink.eguan.result.ResponseResult;
import cn.bluethink.eguan.utils.IdMakerUtils;
import tk.mybatis.mapper.entity.Example;

@Service
public class EgModuleService {

	private IdMakerUtils idMakerUtil = new IdMakerUtils();

	@Autowired
	EgModuleMapper moduleMapper;

	@Autowired
	EgModuleObjectMapper moduleObjectMapper;

	@Autowired
	HttpServletRequest request;

	@Autowired
	EgUserService userService;

	@Autowired
	EgTavernService tavernService;

	/**
	 * 创建服务
	 * 
	 * @return
	 * @throws Exception
	 */
	@Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
	public int create(EgModule module, Long uid) throws Exception {
		// 创建服务id
		Long id = idMakerUtil.nextId();
		// 模型转实体类
		EgModuleEntity egModuleEntity = new EgModuleEntity(module);
		// 服务创建者id
		egModuleEntity.setUid(uid);
		// 服务id
		egModuleEntity.setMid(id);
		// 创建服务之后 审核状态为待审核
		egModuleEntity.setCheckStatus(EgCheckStatus.STATUS_PENDING);
		// 服务创建时间
		egModuleEntity.setCtime(new Date());
		int insert = moduleMapper.insert(egModuleEntity);
		if (insert == 0)
			throw new RuntimeException("创建失败，请重试");
		return insert;

	}

	/**
	 * 更新已创建的服务
	 * 
	 * @return
	 * @throws Exception
	 */
	@Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
	public int update(EgModule module) throws Exception {
		// 查看是否有该服务
		boolean bExists = bExists(module.getId());
		if (bExists)
			return 0;
		// 模型转实体类
		EgModuleEntity egModuleEntity = new EgModuleEntity(module);
		// 服务修改时间
		egModuleEntity.setUtime(new Date());

		int result = moduleMapper.updateByPrimaryKeySelective(egModuleEntity);
		if (result == 0)
			throw new RuntimeException("更新失败，请重试");
		return result;

	}

	/**
	 * 更新已开通的服务
	 * 
	 * @param module
	 * @return
	 * @throws Exception
	 */
	@Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
	public int updateOpenServe(EgModuleObject module) throws Exception {
		// 查看是否有该服务
		boolean bExists = bExists(module.getModule().getId());
		// 查看该服务是否开通
		boolean bOpen = bOpen(module.getModule().getId());
		if (!bExists || !bOpen)
			return 0;
		Long mid = module.getModule().getId();
		Long fid = module.getFaction().getId();
		EgModuleEntity moduleEntity = moduleMapper.selectByPrimaryKey(mid);
		EgModuleobjectEntity entity = new EgModuleobjectEntity();
		// 如果不需要配置
		if (moduleEntity.getbConf() == 0) {
			// 不需要配置却传了服务地址
			if (module.getService() != null) {
				entity.setService("");
			}
		} else {
			// 如果需要配置却没有传服务地址
			if (module.getService() == null)
				entity.setService("");
			entity.setService(module.getService());
		}
		entity.setKey(module.getKey() == null ? "" : module.getKey());
		entity.setUtime(new Date());
		entity.setMid(mid);
		entity.setFid(fid);
		int resule = moduleObjectMapper.updateOpenServe(entity);
		if (resule == 0)
			throw new RuntimeException("更新失败，请重试");
		return resule;

	}

	/**
	 * 删除服务
	 * 
	 * @return
	 * @throws Exception
	 */
	@Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
	public int del(Long mid) throws Exception {
		// 查看该服务是否存在
		boolean bExists = bExists(mid);
		if (bExists)
			return 0;
		// 根据主键物理删除服务
		int result = moduleMapper.deleteByPrimaryKey(mid);
		if (result == 0)
			throw new RuntimeException("删除失败，请重试");
		return result;

	}

	/**
	 * 查询服务是否已经开通
	 * 
	 * @param mid
	 * @return
	 * @throws Exception
	 */
	public boolean bOpen(Long mid) throws Exception {
		// 判断Eg_moduleobject表中是否存在mid
		Example example = new Example(EgModuleobjectEntity.class);
		example.and().andEqualTo("mid", mid);
		int result = moduleObjectMapper.selectCountByExample(example);
		if (result > 0)
			return true;
		return false;

	}

	/**
	 * 服务展示
	 * 
	 * @return
	 */
	public List<EgModule> query() {
		List<EgModuleEntity> result = moduleMapper.selectAll();
		ArrayList<EgModule> module = new ArrayList<>();
		// 实体类转模型
		for (EgModuleEntity entity : result) {
			EgModule m = entity.createModule();
			module.add(m);
		}
		return module;

	}

	/**
	 * 服务开通
	 * 
	 * @param moduleObject
	 * @return
	 * @throws Exception
	 */
	@Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
	public int open(EgModuleObject moduleObject, Long uid, Long fid) throws Exception {
		// 查询服务是否开通
		List<EgModuleobjectEntity> list = moduleObjectMapper.queryByMid(moduleObject.getModule().getId(), fid);
		if (list != null && list.size() > 0)
			return 0;

		// 模型转实体类
		EgModuleobjectEntity entity = new EgModuleobjectEntity(moduleObject, uid, fid);

		Long mid = moduleObject.getModule().getId();
		EgModuleEntity moduleEntity = moduleMapper.selectByPrimaryKey(mid);

		// 如果需要配置的话
		if (moduleEntity.getbConf() == 1) {
			// 需要配置却没传服务地址
			if (moduleObject.getService() == null)
				entity.setService("");
			entity.setService(moduleObject.getService());
			// 如果不需要配置的话
		} else {
			// 不需要配置却传了服务地址
			if (moduleObject.getService() != null)
				entity.setService("");
		}

		int open = moduleObjectMapper.open(entity);
		if (open == 0)
			throw new RuntimeException("开通失败，请重试");
		return open;

	}

	/**
	 * 关闭服务
	 * 
	 * @param mid
	 * @return
	 * @throws Exception
	 */
	@Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
	public int close(Long mid, Long fid) throws Exception {
		// 查看是否有该服务
		Example example = new Example(EgModuleEntity.class);
		example.and().andEqualTo("mid", mid);
		int count = moduleMapper.selectCountByExample(example);
		if (count == 0)
			return 0;
		// 删除eg_moduleobject
		int result = moduleObjectMapper.close(mid, fid);
		if (result == 0)
			throw new RuntimeException("关闭失败，请重试");
		return result;

	}

	/**
	 * 查看该服务是否存在
	 * 
	 * @param mid
	 * @return
	 */
	private boolean bExists(Long mid) {
		// 查看是否有该服务
		Example example = new Example(EgModuleEntity.class);
		example.and().andEqualTo("mid", mid);
		int count = moduleMapper.selectCountByExample(example);
		if (count == 0)
			return false;
		return true;

	}

}
